package com.xavier.lotterysystem.controller;

import com.xavier.lotterysystem.common.error.ControllerErrorCodeConstants;
import com.xavier.lotterysystem.common.exception.ControllerException;
import com.xavier.lotterysystem.common.pojo.CommonResult;
import com.xavier.lotterysystem.common.utils.JacksonUtil;
import com.xavier.lotterysystem.controller.param.UserRegistryParam;
import com.xavier.lotterysystem.controller.result.UserRegistryResult;
import com.xavier.lotterysystem.service.UserService;
import com.xavier.lotterysystem.service.dto.UserRegistryDTO;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 用户注册
     * @param param
     * @return
     */
    @RequestMapping("/registry")
    public CommonResult<UserRegistryResult> userRegistry(
            @Validated @RequestBody UserRegistryParam param){
        logger.info("userRegistry UserRegistryParam:{}", JacksonUtil.writeValueAsString(param));

        UserRegistryDTO userRegistryDTO = userService.registry(param);
        return CommonResult.success(convertToUserRegistryResult(userRegistryDTO));
    }

    private UserRegistryResult convertToUserRegistryResult(UserRegistryDTO userRegistryDTO) {
        UserRegistryResult result = new UserRegistryResult();
        if (null == userRegistryDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegistryDTO.getUserId());
        return result;
    }

}
